package com.mycc.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mycc.lease.common.constant.RedisConstant;
import com.mycc.lease.common.exception.LeaseException;
import com.mycc.lease.common.result.ResultCodeEnum;
import com.mycc.lease.common.utils.JwUtil;
import com.mycc.lease.model.entity.SystemUser;
import com.mycc.lease.model.enums.BaseStatus;
import com.mycc.lease.web.admin.mapper.SystemUserMapper;
import com.mycc.lease.web.admin.service.LoginService;
import com.mycc.lease.web.admin.vo.login.CaptchaVo;
import com.mycc.lease.web.admin.vo.login.LoginVo;
import com.mycc.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.wf.captcha.SpecCaptcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
/**
 * 登录服务实现类，提供登录相关服务的实现。
 */
public class LoginServiceImpl implements LoginService {
    /**
     * 使用Spring框架的自动装配功能，注入Redis模板，以便进行Redis操作。
     */
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SystemUserMapper systemUserMapper;



    /**
     * 获取验证码。
     * <p>
     * 生成一个特定规格的验证码，将其存储到Redis中，并返回包含验证码图像Base64编码和Redis键的Vo对象。
     * 验证码在Redis中设置的过期时间为60秒。
     *
     * @return CaptchaVo 包含验证码图像Base64编码和Redis键的Vo对象。
     */
    @Override
    public CaptchaVo getCaptcha() {
        // 生成一个特定规格的验证码对象
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        // 获取验证码文本并转换为小写
        String code = specCaptcha.text().toLowerCase();
        // 生成一个唯一的键来存储验证码，以防止冲突
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        // 将验证码存储到Redis中，过期时间为60秒
        redisTemplate.opsForValue().set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        // 返回包含验证码图像和键的Vo对象
        return new CaptchaVo(specCaptcha.toBase64(), key);
    }

    @Override
    public String login(LoginVo loginVo) {
        if(Objects.equals(loginVo.getCaptchaCode(), null)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        String code = redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (code == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if (!code.equals(loginVo.getCaptchaCode().toLowerCase())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        SystemUser systemUser = systemUserMapper.selectOneByUsername(loginVo.getUsername());
        if (systemUser == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        if(systemUser.getStatus()== BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        if(!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        return JwUtil.createToken(systemUser.getId(), systemUser.getUsername());
    }

    @Override
    public SystemUserInfoVo getUserInfo(Long userId) {
        SystemUser systemUser = systemUserMapper.selectById(userId);
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}

